package com.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.base.BasePageReq;
import com.base.BasePageRes;
import com.base.BaseServiceImpl;
import com.constant.HandleEnum;
import com.constant.PowerEnum;
import com.constant.StateEnum;
import com.entity.Users;
import com.entity.VipLevel;
import com.entity.VipManage;
import com.entity.VipVoucher;
import com.exception.ServiceException;
import com.repository.VipManageRepository;
import com.req.VipManageReq;
import com.res.UserRes;
import com.res.VipManageRes;
import com.service.VipLevelService;
import com.service.VipManageService;
import com.service.VipVoucherService;
import com.util.DateUtils;
import com.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Calendar;
import java.util.Date;
import java.util.Objects;

@Service
public class VipManageServiceImpl extends BaseServiceImpl<VipManageReq, VipManageRes, VipManageRepository, VipManage> implements VipManageService {
    @Autowired
    private VipVoucherServiceImpl vipVoucherService;
    @Autowired
    private VipLevelServiceImpl vipLevelService;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Override
    public VipManageRes saveVipUser(VipManageReq req) {
        return this.handle(req);
    }

    @Override
    @Transactional
    public VipManageRes open(UserRes user, VipManageReq req) {
        if(StringUtils.isEmpty(req.getVoucherId())){
            throw new ServiceException("请输入vip卷");
        }
        VipVoucher voucher = vipVoucherService.getById(req.getVoucherId());
        StringUtil.throwEmpty(voucher,"无效卷");
        if(!StringUtils.isEmpty( voucher.getIsAvailable())) {
            if (!Objects.equals(voucher.getIsAvailable(), StateEnum.YES.getCode())) {
                throw new ServiceException(String.format("该卷:%s,已经使用过，不能再次使用!", req.getVoucherId()));
            }
        }
        String levelId = voucher.getLevelId();
        VipLevel level = vipLevelService.getById(levelId);
        StateEnum stateEnum = StateEnum.codeOf(level.getVipType());
        StringUtil.throwEmpty(stateEnum,String.format("该卷:%s,无卷类型，无法使用",req.getVoucherId()));
        switch (stateEnum){
            case DOWN:
               req.setCanDownNumber(level.getCanDownNumber());
                break;
            case TIME:
                req.setStartDate(DateUtils.parseDate(new Date(),DateUtils.YYYY_MM_DD));
                //结束日期需要在原有的会员日期上相加
                QueryWrapper<VipManage> vipManageQueryWrapper = new QueryWrapper<>();
                vipManageQueryWrapper.lambda().eq(VipManage::getUserId,user.getId())
                        .eq(VipManage::getIsAvailable, StateEnum.YES.getCode())
                        .eq(VipManage::getVipType,StateEnum.TIME.getCode())
                        .orderByDesc(VipManage::getEndDate)
                ;
                VipManage vipManage = this.getOne(vipManageQueryWrapper);
                if(vipManage!=null) {
                    //在旧会员上加时间
                    req.setEndDate(DateUtils.addDays(vipManage.getEndDate(),level.getDays()+1));
                    //旧的会员设置为无效
                    vipManage.setIsAvailable(StateEnum.NO.getCode());
                    this.saveOrUpdate(vipManage);
                }
                else {
                    //新会员
                    req.setEndDate(DateUtils.addDays(new Date(), level.getDays() + 1));
                }
                break;
                default:
                    break;
        }
        req.setVipType(stateEnum.getCode());
        req.setHandle(HandleEnum.ADD.getCode());
        req.setIsAvailable(StateEnum.YES.getCode());
        req.setLevelId(levelId);
        req.setUserId(user.getId());
        voucher.setIsAvailable(StateEnum.NO.getCode());
        vipVoucherService.saveOrUpdate(voucher);
        //修复开能会员后不能立即下载的bug 后端需要更新redis,前端需要缓存
        user.setVip(StateEnum.YES.getCode());
        redisTemplate.opsForValue().set(user.getKey(), JSONObject.toJSONString(user));
        VipManageRes manageRes = this.add(req);
        manageRes.setUserRes(user);
        return manageRes;
    }

    @Override
    public BasePageRes queryPage(BasePageReq req,UserRes userRes) {
        if (StringUtils.isEmpty(req.getPage())) {
            throw new ServiceException("请传入page");
        }
        if (StringUtils.isEmpty(req.getSize())) {
            throw new ServiceException("请传入size");
        }


        QueryWrapper<VipManage> wrapper = new QueryWrapper<>();
        PowerEnum powerEnum = PowerEnum.codeOf(userRes.getPower());
        switch (powerEnum) {
            case Admin:
                break;
            case Users:
                wrapper.lambda().and(Wrapper -> Wrapper.eq(VipManage::getUserId, userRes.getId()));
                break;
            default:
                break;
        }
        wrapper.lambda().orderByDesc(VipManage::getEndDate);
        if (!StringUtils.isEmpty(req.getDes())) {
            wrapper.lambda().and(Wrapper->Wrapper.like(VipManage::getLevelId, req.getDes())
                    .or().like(VipManage::getVoucherId,req.getDes())
                    .or().like(VipManage::getIsAvailable,req.getDes()))
            ;


        }


        IPage<VipManage> pages = new Page<>(req.getPage(), req.getSize());
        IPage<VipManage> articalIPage = this.page(pages, wrapper);
        BasePageRes pageRes = this.convertIpage(articalIPage, new VipManageRes());

        return pageRes;
    }
}
